package com.xqc.shop.account;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.sql.DataSource;

@SpringBootApplication
@EnableDiscoveryClient
//@EnableCircuitBreaker//开启服务降级
@EnableFeignClients(basePackages={"com.xqc.shop.order.service","com.xqc.shop.stock.service"})
public class ShopAccountServiceApplication7009 {
    public static void main( String[] args ){
        SpringApplication.run(ShopAccountServiceApplication7009.class, args);
    }
    
    //redis序列化设置，spring-data-redis的RedisTemplate默认是JdkSerializationRedisSerializer来进行序列化，值是十六进制，例如本身要存的key:tb，但实际上存的是\xac\xed\x00\x05t\x00\tb
    @Bean
    public RedisTemplate<String, Object> setRedisTemplate(RedisConnectionFactory factory) {
    	 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    	 RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    	 redisTemplate.setKeySerializer(redisSerializer);
    	 redisTemplate.setConnectionFactory(factory);
    	// 自定义Jackson2JsonRedisSerializer
    	 Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
    	 redisTemplate.setValueSerializer(serializer);
    	 redisTemplate.afterPropertiesSet();
    	 return redisTemplate;
    }
    
    /**
     * redisson支持
     * @return
     */
    @Bean
    public RedissonClient getRedisson() {
    	return Redisson.create();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 需要将 DataSourceProxy 设置为主数据源，否则事务无法回滚
     * @param druidDataSource The DruidDataSource
     * @return The default datasource
     */
    @Primary
    @Bean("dataSource")
    public DataSource dataSource(DruidDataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }
}
